package com.yidu.role.controller;

import com.yidu.role.entity.PerRole;
import com.yidu.role.entity.PerUser;
import com.yidu.role.service.PerRoleService;
import com.yidu.role.service.UserClient;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 角色表(PerRole)表控制层
 *
 * @author liandyao
 * @since 2020-07-21 10:00:46
 */
@RestController
@RequestMapping("perRole")
public class PerRoleController {
    public Logger logger = LoggerFactory.getLogger(PerRoleController.class);
    /**
     * 服务对象
     */
    @Resource
    private PerRoleService perRoleService;

    @Resource
    RestTemplate restTemplate;

    @Resource
    DiscoveryClient discoveryClient ;

    @Resource
    private UserClient userClient;


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public PerRole selectOne(Integer id) {
        return this.perRoleService.queryById(id);
    }

    @GetMapping("selectUser/{id}")
    public PerUser selectUser(@PathVariable("id") Integer id){
        logger.info("传过来的Id是:"+id);
        //使用Java代码请求get.post.put.delete
        /*String url = "http://localhost:8080/user/4";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        try {
            Response response=call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }*/

       // String serviceId = "USERMICROSERVICE";
       /* List<ServiceInstance> list =
                discoveryClient.getInstances(serviceId);

        if(list.isEmpty()){
            logger.info("找不到<"+serviceId+">这个实例");
        }else{
            logger.info("找到<"+serviceId+">"+list.size()+"个实例");
        }
        //返回第一个
        ServiceInstance instance = list.get(0);

        String url = "http://"+instance.getHost()+":"+instance.getPort()+"user/"+id;*/
      // String url = "http://"+serviceId+"/user/"+id;
      // PerUser user = restTemplate.getForObject(url, PerUser.class);
       // return  userClient.findById(id) ;
        PerUser user = this.perRoleService.findByUser(id);
        return user ;
    }
}